package org.jmc.refmanager.web.wicket.form;

import java.util.Date;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.jmc.refmanager.domain.model.OrgUnit;
import org.jmc.refmanager.domain.service.OrgUnitManager;
import org.jmc.refmanager.jsr303validators.JSR303FormValidator;
import org.jmc.refmanager.security.SecurityHelper;
import org.jmc.refmanager.web.wicket.page.search.ServicesListPage;

public class ServiceDeleteForm extends Form<OrgUnit> {
	private static final long serialVersionUID = 1L;
	
	@SpringBean(name="orgUnitManager")
	private OrgUnitManager orgUnitManager;

	/**
	 * @param id
	 * @param model
	 */
	public ServiceDeleteForm(String id, IModel<OrgUnit> model) {
		super(id, new CompoundPropertyModel<OrgUnit>(model));
		setOutputMarkupId(false);
		final String matricule = SecurityHelper.getAuthentication().getName();
		
		TextArea<String> motif = new TextArea<String>("motifSuppression");
		motif.setRequired(true);
		add(motif);

		RequiredTextField<Date> dateFin = new RequiredTextField<Date>("dateFin", new PropertyModel<Date>(model, "dateFin"), Date.class);
//		dateFin.add(new DatePicker() {
//			private static final long serialVersionUID = 1L;
//
//			/* (non-Javadoc)
//			 * @see org.apache.wicket.extensions.yui.calendar.DatePicker#getDatePattern()
//			 */
//			@Override
//			protected String getDatePattern() {
//				return "dd/MM/yyyy";
//			}
//		});
		dateFin.setOutputMarkupId(false);
		add(dateFin);

		// Validateur JSR303
		add(new JSR303FormValidator());
		
		OrgUnit service = getModelObject();
		Integer countChildren = orgUnitManager.countChildren(service.getId(), matricule);
		
		boolean canDelete = (countChildren == null || countChildren == 0);
		if (!canDelete) {
			warn("L'ensemble des services fils doivent être supprimés avant de pouvoir supprimer ce service.");
		}
		Button btnSubmit = new Button("btnSubmit");
		add(btnSubmit);
		
		Button btnCancel = new Button("btnCancel") {
			private static final long serialVersionUID = 1L;
			@Override
			public void onSubmit() {
				// Affiche le message sur la page redirigee
				warn("Aucune suppression n'a été réalisée");
				setResponsePage(ServicesListPage.class);
			}
		};
		// Pas de validation
		btnCancel.setDefaultFormProcessing(false);
		add(btnCancel);
		
		// Masque le formulaire s'il existe des fils
		setVisible(canDelete);
	}


}
